package com.hejjon.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hejjon.core.domain.entity.Connection;
import com.hejjon.core.exception.BusinessException;
import com.hejjon.core.utils.AESUtil;
import com.hejjon.mapper.ConnectionMapper;
import com.hejjon.pojo.ConnectionInfo;
import com.hejjon.service.IConnectionService;
import com.hejjon.util.JDBCUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: cs
 * @date: 2025-02-20 15:16:09
 * @since: 1.0
 */
@Service
public class ConnectionServiceImpl extends ServiceImpl<ConnectionMapper, Connection> implements IConnectionService {


    @Override
    public boolean createConn(Connection param) {

        String url = JDBCUtils.getUrlByInfo(param.getHost(), param.getPort(), param.getDriveType());
        param.setUrl(url);
        param.setCreateBy("admin");
        param.setCreateTime(LocalDateTime.now());

        return save(param);
    }

    @Override
    public boolean testConnect(Connection param) {

        String encryptPwd, decryptPwd;
        String id = param.getId();
        Connection c;
        if (StringUtils.isEmpty(id)) {
            c = param;
        } else {
            c = getById(id);
            if (c == null) {
                return false;
            }
        }
        // 解密密码
        encryptPwd = c.getPassword();
        decryptPwd = AESUtil.decryptByAES(encryptPwd);
        c.setPassword(decryptPwd);
        // 拼接 url
        String url = JDBCUtils.getUrlByInfo(c.getHost(), c.getPort(), c.getDriveType());
        c.setUrl(url);
        ConnectionInfo conn = new ConnectionInfo(c);
        java.sql.Connection connection = JDBCUtils.takeJdbcConnection(conn);
        return connection != null;
    }

    @Override
    public List<Connection> findConnectionList() {

        return list();
    }

    @Override
    public boolean update(Connection conn) {
        String id = conn.getId();
        Connection connection = getById(id);
        if (connection == null) {
            return false;
        }

        connection.setName(conn.getName());
        connection.setHost(conn.getHost());
        connection.setPort(conn.getPort());
        connection.setDescription(conn.getDescription());
        connection.setDriveType(conn.getDriveType());
        connection.setUrl(conn.getUrl());
        connection.setUpdateBy("admin");
        connection.setUpdateTime(LocalDateTime.now());
        return updateById(connection);
    }

    @Override
    public int batchRemove(List<String> ids) {
        if (ids.size() == 0) {
            throw new BusinessException("id列表为空!");
        }

        return baseMapper.deleteBatchIds(ids);
    }
}
